package cn.itcast.mq.bean.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
public class BeanRabbitErrorConfig {

    public static final String DIRECT_ERROR_EXCHANGE = "direct.error.exchange";

    public static final String DIRECT_ROUTEKEY_ERROR = "direct.error";

    public static final String DIRECT_ERROR_QUEUE = "direct.error.queue";

    @Bean
    public DirectExchange directErrorExchange() {
        return new DirectExchange(DIRECT_ERROR_EXCHANGE);
    }

    @Bean
    public Queue directErrorQueue() {
        return new Queue(DIRECT_ERROR_QUEUE);
    }

    @Bean
    public Binding directErrorBinding(Queue directErrorQueue, DirectExchange directErrorExchange) {
        return BindingBuilder.bind(directErrorQueue).to(directErrorExchange).with(DIRECT_ROUTEKEY_ERROR);
    }

    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate, DIRECT_ERROR_EXCHANGE, DIRECT_ROUTEKEY_ERROR);
    }

}
